<?php

class DIR {
  var $conn;

  function __construct( $servername, $username, $password, $dbname){
    $this->conn = new mysqli($servername, $username, $password, $dbname);
    if ($this->conn->connect_error){
      $this->conn = -1;
      return;
    }
    $this->conn->set_charset("utf8");
  }

  function __destruct(){
    $this->conn->close();
  }

  function add($parent, $name, $uid){
    $stmtdir = $this->conn->prepare('INSERT INTO bkmk_dir ( parent, name, uid ) VALUES ( ?, ?, ? )');

    $stmtdir->bind_param('isi', $parent, $name, $uid);
    $stmtdir->execute();

    $stmtdir->close();

    return true;
  }

  function alt($id, $parent, $name, $subdir, $file, $uid){
    $stmtdir = $this->conn->prepare('UPDATE bkmk_dir SET parent = ?, name = ?, subdir = ?, file = ?, uid = ? WHERE id = ?');

    $stmtdir->bind_param('isiiii', $parent, $name, $subdir, $file, $uid, $id);
    $stmtdir->execute();

    $stmtdir->close();

    return true;
  }

  function getById($id){
    $stmtdir = $this->conn->prepare('SELECT id, parent, name, subdir, file, uid FROM bkmk_dir WHERE id = ?');

    $stmtdir->bind_param('i', $id);
    $stmtdir->execute();
    $stmtdir->store_result();
    $stmtdir->bind_result($rid, $rparent, $rname, $rsubdir, $rfile, $ruid);

    if($stmtdir->fetch()){

      $data = array();
      $data['id']     = $rid;
      $data['parent'] = $rparent;
      $data['name']   = $rname;
      $data['subdir'] = $rsubdir;
      $data['file']   = $rfile;
      $data['uid']    = $ruid;

    }else{

      $data = false;

    }

    $stmtdir->close();

    return $data;
  }

  function delById($id){
    #获得所有子目录
    $subdirs = $this->getAllSubDirIds($id);
    #加入当前目录ID获得所有需要删除的目录ID
    array_push($subdirs, $id);
    $deldirs = $subdirs;

    #准备目录和文件删除语句
    $stmtDelDir = $this->conn->prepare('DELETE FROM bkmk_dir WHERE id = ?');
    $stmtDelFil = $this->conn->prepare('DELETE FROM bkmk_fil WHERE parent = ?');

    foreach($deldirs as $deldir){
      #删除目录
      $stmtDelDir->bind_param('i', $deldir);
      $stmtDelDir->execute();
      #删除目录下的文件
      $stmtDelFil->bind_param('i', $deldir);
      $stmtDelFil->execute();
    }

    $stmtDelDir->close();
    $stmtDelFil->close();

    return true;
  }

  function getAllSubDirIds($cId){
    #初始化结果数组
    $subdirs = array();

    #获得所有子目录
    $stmtGetSubDir = $this->conn->prepare('SELECT id FROM bkmk_dir WHERE parent = ?');
    $stmtGetSubDir->bind_param('i', $cId);
    $stmtGetSubDir->execute();
    $stmtGetSubDir->store_result();
    $stmtGetSubDir->bind_result($rid);
    while($stmtGetSubDir->fetch()){
      array_push($subdirs, $rid);
    }

    $stmtGetSubDir->close();

    $subsubdirs = array();
    #对于每个子目录，获得所有次级子目录，递归调用
    foreach($subdirs as $subdir){
      $subsubdirs = array_merge($subsubdirs, $this->getAllSubDirIds($subdir));
    }

    #合并所有子目录和子目录的子目录
    $result = array_merge($subdirs, $subsubdirs);

    return $result;
  }
}

